﻿///////////////////////////////////////////////////////////////////////////////
// File:        SocketThread.cc
// Author:      671643387@qq.com
// Date:        2016年1月5日 下午5:43:52
// Description:
///////////////////////////////////////////////////////////////////////////////

#include "SocketThread.hpp"

namespace fog
{
    namespace net
    {
        SocketThread::SocketThread(void)
            : evBase_(NULL)
            , load_(0)
        {

        }

        SocketThread::~SocketThread(void)
        {

        }

        bool SocketThread::open(bool notCreateThread /* = false */)
        {
            do 
            {
                evBase_ = event_base_new();
                if (!evBase_) break;

                evDummy_ = event_new(evBase_, -1, 
                    EV_TIMEOUT | EV_PERSIST, onDummy, this);
                if (!evDummy_) break;

                struct timeval tv = { 1, 0 };
                if (0 != event_add(evDummy_, &tv))
                    break;

                return true;
            } while (false);

            doClose();

            return false;
        }

        void SocketThread::stop(void)
        {
            event_base_loopbreak(evBase_);
        }

        void SocketThread::run(void)
        {
            event_base_dispatch(evBase_);
            doClose();
        }

        void SocketThread::doClose(void)
        {
            if (evDummy_)
            {
                event_free(evDummy_);
                evDummy_ = NULL;
            }

            if (evBase_)
            {
                event_base_free(evBase_);
                evBase_ = NULL;
            }
        }

        void SocketThread::onDummy(evutil_socket_t sock, short event, void* arg)
        {

        }
    }
}